﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Zen.Barcode;

namespace Worktool
{
    public partial class Commissioning : Form
    {
        List<string> listeVenue = new List<string> { };
        List<string> listePackstuecke = new List<string> { };
        List<string> listeSerials = new List<string> { };
        List<string> listeSerialPositionen = new List<string> { };
        String pkInstalledPrinters;
        PrintDocument label;
        PrintDocument palettenzettel;
        int indexVenue = 0;
        int indexPackstueck = 0;
        int indexPosition = -1;
        int indexSerial = -1;
        private string labelSerialNumber = "";
        private string labelManufacturer = "";
        private string labelModel = "";
        private string labelPosition = "";
        private string labelVenue = "";
        private string labelJLM = "";
        private string labelTa1 = "";
        private string labelTa2 = "";
        private string labelTa3 = "";
        bool print = true;
        bool booking = true;

        
        public Commissioning()
        {
            InitializeComponent();
        }

        private void Commissioning_Load(object sender, EventArgs e)
        {
            this.Text = "Commissioning: " + Properties.Settings.Default.CurrentDBName; 
            this.vw_comm_SerialsTableAdapter.Fill(this.aSCDataSet.vw_comm_Serials);
            this.vw_lbl_SerialsTableAdapter.Fill(this.aSCDataSet.vw_lbl_Serials);
            this.vw_eng_MaterialDetailTableAdapter.Fill(this.aSCDataSet.vw_eng_MaterialDetail);
            this.vw_comm_materialTotalTableAdapter.Fill(this.aSCDataSet.vw_comm_materialTotal);
            this.sTAMMDATEN_areasTableAdapter.Fill(this.aSCDataSet.STAMMDATEN_areas);
            this.tbl_systemDataTableAdapter1.Fill(this.aSCDataSet.tbl_systemData);
            
            
            // Drucker in das Auswahlfeld eintragen
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
                comboBox3.Items.Add(pkInstalledPrinters);
                comboBox4.Items.Add(pkInstalledPrinters);
            }
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                if (Properties.Settings.Default.LabelPrinterName == PrinterSettings.InstalledPrinters[i])
                {
                    comboBox3.Text = Properties.Settings.Default.LabelPrinterName;
                    comboBox4.Text = Properties.Settings.Default.LabelPrinterName;
                }
            }

            // Venueliste aus Dataset füllen
            listeVenue = aSCDataSet.STAMMDATEN_areas.AsEnumerable()
                         .Select(r => r.Field<string>("Venue"))
                         .ToList();

            // aktuelle Packstücknummer holen
            textBox3.Text = aSCDataSet.tbl_systemData[aSCDataSet.tbl_systemData.Rows.Count-1]["letztesPackstueck"].ToString();
            button12.Text = textBox3.Text;

            // Seriennummernliste füllen
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                listeSerials.Add(dataGridView1.Rows[i].Cells["serialNumber"].Value.ToString());
            }

            // Die Ansichten entsprechend vorfiltern
            vwcommmaterialTotalBindingSource.Filter = string.Format("isBulk = 1");
            // Starteinstellungen ohne Venue und ohne Packstücke
            comboBox1.Text = "";
            vwengMaterialDetailBindingSource.Filter = string.Format("Venue LIKE ''");

            // Eventhandler für Tabellen starten
            this.dataGridView3.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView3_CellValueChanged);
            
          

        }

        //
        // Venue wechselt
        //
        private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            vwengMaterialDetailBindingSource.Filter = string.Format("Venue LIKE '{0}'", (comboBox1.Text+"*"));
            // Liste der gebuchten Seriennummern löschen und neu erstellen
            listeSerialPositionen.RemoveRange(0, listeSerialPositionen.Count);
            for (int i = 0; i < dataGridView3.RowCount; i++)
            {
                // Liste aus allen bereits in dem Venue gebuchten Seriennummern erstellen
                listeSerialPositionen.Add(dataGridView3.Rows[i].Cells["dgv3Seriennummer"].Value.ToString());
            }
            //if (comboBox1.Text != "") // Nicht beim Start aufrufen
            //{

            //    DialogResult dialogresult = MessageBox.Show("Venue gewechselt. Neue Packstücknummer erstellen ?", "Venuewechsel", MessageBoxButtons.YesNo);
            //    if (dialogresult == DialogResult.Yes)
            //    {
            //        // um eins erhöhen und in die DB schreiben
            //        aSCDataSet.tbl_systemData[aSCDataSet.tbl_systemData.Rows.Count - 1]["letztesPackstueck"] = (Convert.ToInt32(aSCDataSet.tbl_systemData[aSCDataSet.tbl_systemData.Rows.Count - 1]["letztesPackstueck"]) + 1);
            //        tbl_systemDataTableAdapter1.Update(aSCDataSet);

            //        // und wieder zurücklesen aus DB
            //        textBox3.Text = aSCDataSet.tbl_systemData[aSCDataSet.tbl_systemData.Rows.Count - 1]["letztesPackstueck"].ToString();
            //        button12.Text = textBox3.Text;

            //        // und Packzettel für Palette ausdrucken
            //        palettenzettel = new PrintDocument();
            //        PaperSize pS = new PaperSize();
            //        pS.RawKind = (int)PaperKind.A4Rotated;
            //        palettenzettel.DefaultPageSettings.PaperSize = pS;
            //        palettenzettel.PrinterSettings.PrinterName = comboBox4.Text;
            //        palettenzettel.PrinterSettings.DefaultPageSettings.PaperSize = pS;
            //        palettenzettel.PrintPage += new PrintPageEventHandler(palettenzettel_PrintPage);

            //        if (print && comboBox4.Text != "")
            //        {
            //            palettenzettel.Print();
            //            palettenzettel.Print();
            //        }
            //    }
            //}

            textBox1.Focus();
        }

        //
        // Seriennummerneingabe prüfen und Buchung vornehmen
        //
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {

            string suchModel = "";
            string suchManufacturer = "";

            // Enter Taste gedrückt und Textbox nicht leer  ?
            if (e.KeyCode == Keys.Enter && textBox1.Text != "")
            {
                // Ist die Seriennummer vielleicht schon auf eine Position gebucht ?
                #region gebucht
                if (listeSerialPositionen.Contains(textBox1.Text)) // Liste aller in dem Venue vorhandenen Seriennummern durch suchen
                {
                    // Den richtigen Eintrag im MatDetail suchen
                    for (int i = 0; i < dataGridView3.RowCount; i++)
                    {
                        if (dataGridView3.Rows[i].Cells["dgv3Seriennummer"].Value.ToString() == textBox1.Text)
                        {
                            indexPosition = i; // Die Zeile in der die Seriennummer gefunden wurde
                            if (dataGridView3.Rows[indexPosition].Cells["dgv3packstueck"].Value.ToString() != "") // Ist diese Seriennummer schon einmal auf ein Packstück gebucht worden ?
                            {
                                DialogResult dialogresult = MessageBox.Show("Vorsicht! Diese Seriennummer wurde schon auf eine Palette gebucht. Trotzdem fortfahren?", "Buchungsfehler", MessageBoxButtons.YesNo);
                                if (dialogresult == DialogResult.Yes)
                                {
                                    if (booking)
                                    {
                                        dataGridView3.Rows[indexPosition].Cells["dgv3packstueck"].Value = Convert.ToInt32(textBox3.Text);
                                        vw_eng_MaterialDetailTableAdapter.updateMaterialExtended(dataGridView3.Rows[indexPosition].Cells["dgv3packstueck"].Value.ToString(), Convert.ToInt32(dataGridView3.Rows[indexPosition].Cells["IDMaterialExtended"].Value));
                                    }
                                }
                                else
                                {
                                }
                            }
                            else // Wurde noch nicht auf ein Packstück gebucht
                            {
                                if (booking)
                                {
                                    dataGridView3.Rows[indexPosition].Cells["dgv3packstueck"].Value = Convert.ToInt32(textBox3.Text);
                                    vw_eng_MaterialDetailTableAdapter.updateMaterialExtended(dataGridView3.Rows[indexPosition].Cells["dgv3packstueck"].Value.ToString(), Convert.ToInt32(dataGridView3.Rows[indexPosition].Cells["IDMaterialExtended"].Value));
                                }
                            }

                        }
                    }
                    labelSerialNumber = dataGridView3.Rows[indexPosition].Cells["dgv3Seriennummer"].Value.ToString();
                    labelManufacturer = dataGridView3.Rows[indexPosition].Cells["dgv3Manufacturer"].Value.ToString();
                    labelModel = dataGridView3.Rows[indexPosition].Cells["dgv3Model"].Value.ToString();
                    labelPosition = dataGridView3.Rows[indexPosition].Cells["dgv3Position"].Value.ToString();
                    labelVenue = dataGridView3.Rows[indexPosition].Cells["dgv3Venue"].Value.ToString();
                    labelJLM = dataGridView3.Rows[indexPosition].Cells["dgv3JLM"].Value.ToString();
                    labelTa1 = dataGridView3.Rows[indexPosition].Cells["dgv3Ta1"].Value.ToString();
                    labelTa2 = dataGridView3.Rows[indexPosition].Cells["dgv3Ta2"].Value.ToString();
                    labelTa3 = dataGridView3.Rows[indexPosition].Cells["dgv3Ta3"].Value.ToString();
                    
                    label = new PrintDocument();
                    PaperSize pS = new PaperSize("Custom Size", 620, 350);
                    label.DefaultPageSettings.PaperSize = pS;
                    label.PrinterSettings.PrinterName = comboBox3.Text;
                    label.PrinterSettings.DefaultPageSettings.PaperSize = pS;
                    label.PrintPage += new PrintPageEventHandler(label_PrintPage);

                    if (print && comboBox3.Text != "")
                    {
                        label.Print();
                        label.Print();
                    }
                    // Druckstrings sicherheitshalber wieder zurück setzen
                    labelSerialNumber = "";
                    labelManufacturer = "";
                    labelModel = "";
                    labelPosition = "";
                    labelVenue = "";
                    labelJLM = "";
                    labelTa1 = "";
                    labelTa2 = "";
                    labelTa3 = "";


                    dataGridView4.Rows.Add();
                    dataGridView4.Rows[dataGridView4.RowCount-1].Cells["Time"].Value = DateTime.Now.ToShortTimeString();
                    dataGridView4.Rows[dataGridView4.RowCount-1].Cells["Event"].Value = "Already booked Serial " + textBox1.Text + " confirmed and printed";
                    textBox1.Text = "";

                }
                #endregion gebucht
                // Ist die Seriennummer in den Seriennummern ?
                #region vorhanden
                else if (listeSerials.Contains(textBox1.Text))
                {
                    // Den richtigen Eintrag in den Seriennummern suchen
                    for (int i = 0; i < dataGridView1.RowCount; i++)
                    {
                        if (dataGridView1.Rows[i].Cells["serialNumber"].Value.ToString() == textBox1.Text)
                        {
                            indexSerial = i;
                        }
                    }
                    // Den korrespondierenden Eintrag im Material suchen
                    suchManufacturer = dataGridView1.Rows[indexSerial].Cells["Manufacturer"].Value.ToString();
                    suchModel = dataGridView1.Rows[indexSerial].Cells["Model"].Value.ToString();
                    for (int i = 0; i < dataGridView3.RowCount; i++)
                    {
                        if (dataGridView3.Rows[i].Cells["dgv3Manufacturer"].Value.ToString() == suchManufacturer && dataGridView3.Rows[i].Cells["dgv3Model"].Value.ToString() == suchModel && dataGridView3.Rows[i].Cells["dgv3Seriennummer"].Value.ToString() == "")
                        {
                            indexPosition = i;
                        }
                    }
                    // Vielleicht schon vergeben ?
                    if (indexPosition == -1)
                    {
                        dataGridView4.Rows.Add();
                        dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Time"].Value = DateTime.Now.ToShortTimeString();
                        dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Event"].Value = "Serial " + textBox1.Text + " is already booked in this Venue ";
                        textBox1.Text = "";
                    }
                    else 
                    {
                        // Jetzt die Zuweisung
                        // erst die Seriennummer
                        dataGridView3.Rows[indexPosition].Cells["dgv3Seriennummer"].Value = dataGridView1.Rows[indexSerial].Cells["serialNumber"].Value.ToString();
                        
                        // Packstücknummer schreiben, wenn nicht schon vergeben
                        if (booking)
                        {
                            if (dataGridView3.Rows[indexPosition].Cells["dgv3packstueck"].Value.ToString() != "")
                            {
                                // Schon vergeben
                                DialogResult dialogresult = MessageBox.Show("Vorsicht! Diese Seriennummer wurde schon auf eine Palette gebucht. Trotzdem fortfahren?", "Buchungsfehler", MessageBoxButtons.YesNo);
                                if (dialogresult == DialogResult.Yes)
                                {
                                    dataGridView3.Rows[indexPosition].Cells["dgv3packstueck"].Value = Convert.ToInt32(textBox3.Text);
                                    vw_eng_MaterialDetailTableAdapter.updateMaterialExtended(dataGridView3.Rows[indexPosition].Cells["dgv3packstueck"].Value.ToString(), Convert.ToInt32(dataGridView3.Rows[indexPosition].Cells["IDMaterialExtended"].Value));
                                }
                                else
                                {
                                }
                            }
                            else // noch nicht vergeben
                            {
                                dataGridView3.Rows[indexPosition].Cells["dgv3packstueck"].Value = Convert.ToInt32(textBox3.Text);
                                vw_eng_MaterialDetailTableAdapter.updateMaterialExtended(dataGridView3.Rows[indexPosition].Cells["dgv3packstueck"].Value.ToString(), Convert.ToInt32(dataGridView3.Rows[indexPosition].Cells["IDMaterialExtended"].Value));
                            }
                        }

                        vwengMaterialDetailBindingSource.EndEdit();
                        vw_eng_MaterialDetailTableAdapter.Update(aSCDataSet);
                        vw_eng_MaterialDetailTableAdapter.updateMaterialExtended(dataGridView3.Rows[indexPosition].Cells["dgv3packstueck"].Value.ToString(), Convert.ToInt32(dataGridView3.Rows[indexPosition].Cells["IDMaterialExtended"].Value));
                        // Zugehöriges Label ausdrucken
                        labelSerialNumber = dataGridView3.Rows[indexPosition].Cells["dgv3Seriennummer"].Value.ToString();
                        labelManufacturer = dataGridView3.Rows[indexPosition].Cells["dgv3Manufacturer"].Value.ToString();
                        labelModel = dataGridView3.Rows[indexPosition].Cells["dgv3Model"].Value.ToString();
                        labelPosition = dataGridView3.Rows[indexPosition].Cells["dgv3Position"].Value.ToString();
                        labelVenue = dataGridView3.Rows[indexPosition].Cells["dgv3Venue"].Value.ToString();
                        labelJLM = dataGridView3.Rows[indexPosition].Cells["dgv3JLM"].Value.ToString();
                        labelTa1 = dataGridView3.Rows[indexPosition].Cells["dgv3Ta1"].Value.ToString();
                        labelTa2 = dataGridView3.Rows[indexPosition].Cells["dgv3Ta2"].Value.ToString();
                        labelTa3 = dataGridView3.Rows[indexPosition].Cells["dgv3Ta3"].Value.ToString();

                        label = new PrintDocument();
                        PaperSize pS = new PaperSize("Custom Size", 620, 350);
                        label.DefaultPageSettings.PaperSize = pS;
                        label.PrinterSettings.PrinterName = comboBox3.Text;
                        label.PrinterSettings.DefaultPageSettings.PaperSize = pS;
                        label.PrintPage += new PrintPageEventHandler(label_PrintPage);

                        if (print && comboBox3.Text != "")
                        {
                            label.Print();
                            label.Print();
                        }

                        // Log schreiben
                        dataGridView4.Rows.Add();
                        dataGridView4.Rows[dataGridView4.RowCount-1].Cells["Time"].Value = DateTime.Now.ToShortTimeString();
                        dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Event"].Value = "Serial " + textBox1.Text + " booked to " + labelManufacturer.ToString() + " - " + labelModel.ToString() +" - " + labelPosition.ToString();
                        textBox1.Text = "";

                        // Druckstrings sicherheitshalber wieder zurück setzen
                        labelSerialNumber = "";
                        labelManufacturer = "";
                        labelModel = "";
                        labelPosition = "";
                        labelVenue = "";
                        labelJLM = "";
                        labelTa1 = "";
                        labelTa2 = "";
                        labelTa3 = "";
                    }

                    
                    // Liste der vorhandenen Seriennummern updaten, damit sie nicht neu vergeben werden kann

                    listeSerialPositionen.RemoveRange(0, listeSerialPositionen.Count);
                    for (int i = 0; i < dataGridView3.RowCount; i++)
                    {
                        listeSerialPositionen.Add(dataGridView3.Rows[i].Cells["dgv3Seriennummer"].Value.ToString());
                    }

                }
                #endregion vorhanden
                // Gibt es die Seriennummer nicht ?
                #region neu
                else 
                {
                    dataGridView4.Rows.Add();
                    dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Time"].Value = DateTime.Now.ToShortTimeString();
                    dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Event"].Value = "Serial " + textBox1.Text + " was not found in this Venue ";
                    textBox1.Text = "";
                }
                #endregion neu
            }
        }

        //
        // Print Eventhandler
        //
        private void label_PrintPage(object sender, PrintPageEventArgs e)
        {

            SolidBrush brush = new SolidBrush(Color.Black);
            System.Drawing.Font header = new System.Drawing.Font(FontFamily.GenericSansSerif, 8.0F, FontStyle.Bold);
            Code128BarcodeDraw barcode128 = BarcodeDrawFactory.Code128WithChecksum;
            Image img;

            e.Graphics.DrawString("Venue: " + labelVenue, header, brush, 5, 5);
            e.Graphics.DrawString("Manufacturer: " + labelManufacturer, header, brush, 5, 17);
            e.Graphics.DrawString("Model: " + labelModel, header, brush, 5, 29);
            e.Graphics.DrawString("SN: " + labelSerialNumber, header, brush, 5, 41);
            e.Graphics.DrawString("JLM: " + labelJLM, header, brush, 5, 53);
            e.Graphics.DrawString("Position: " + labelPosition, header, brush, 5, 65);
            e.Graphics.DrawString(labelTa1, header, brush, 5, 77);
            e.Graphics.DrawString(labelTa2, header, brush, 5, 89);
            e.Graphics.DrawString(labelTa3, header, brush, 5, 101);

            e.Graphics.DrawImage(Worktool.Properties.Resources.ASC_Logo_quadratisch, 200, 10, 30, 30);
            if (labelSerialNumber != null && labelSerialNumber != "")
            {
                img = barcode128.Draw(labelSerialNumber, 30);
                e.Graphics.DrawImage(img, 5, 113);
            }


            
                    
        }

        //
        // Drucken ein und ausschalten
        //
        private void button3_Click(object sender, EventArgs e)
        {
        
        
            if (print)
            {
                button3.Text = "Printing Off";
                button3.BackColor = Color.Red;
                print = !print;
            }
            else
            {
                button3.Text = "Printing On";
                button3.BackColor = Color.Green;
                print = !print;
            }
        }

        //
        // Datenquellen zurücksetzen, wenn geschlossen wird
        //
        private void Commissioning_FormClosing(object sender, FormClosingEventArgs e)
        {
            dataGridView1.DataSource = null;
            dataGridView2.DataSource = null;
            dataGridView3.DataSource = null;
            dataGridView4.DataSource = null;

        }

        //
        // Venueliste zu Excel ausgeben
        //
        private void button4_Click(object sender, EventArgs e)
        {
            dataGridView3.SelectAll();
            DataObject dataObj = dataGridView3.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView3.ClearSelection();
        }


        //
        // Seriennummern zu Excel ausgeben
        //
        private void button5_Click(object sender, EventArgs e)
        {

            dataGridView1.SelectAll();
            DataObject dataObj = dataGridView1.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView1.ClearSelection();
        }

        //
        // Bulk zu Excel ausgeben
        //
        private void button6_Click(object sender, EventArgs e)
        {
            dataGridView2.SelectAll();
            DataObject dataObj = dataGridView2.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView2.ClearSelection();
        }

        //
        // Log zu Excel ausgeben
        //
        private void button7_Click(object sender, EventArgs e)
        {
            dataGridView4.SelectAll();
            DataObject dataObj = dataGridView4.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView4.ClearSelection();
        }

        private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }


        //
        // Packstücknummer erhöhen
        //
        private void button8_Click(object sender, EventArgs e)
        {
            // um eins erhöhen und in die DB schreiben
            aSCDataSet.tbl_systemData[aSCDataSet.tbl_systemData.Rows.Count - 1]["letztesPackstueck"] = (Convert.ToInt32(aSCDataSet.tbl_systemData[aSCDataSet.tbl_systemData.Rows.Count - 1]["letztesPackstueck"]) + 1);
            tbl_systemDataTableAdapter1.Update(aSCDataSet);
            
            // und wieder zurücklesen aus DB
            textBox3.Text = aSCDataSet.tbl_systemData[aSCDataSet.tbl_systemData.Rows.Count - 1]["letztesPackstueck"].ToString();
            
            // und Packzettel für Palette ausdrucken
            palettenzettel = new PrintDocument();
            PaperSize pS = new PaperSize();
            pS.RawKind = (int)PaperKind.A4Rotated;
            palettenzettel.DefaultPageSettings.PaperSize = pS;
            palettenzettel.PrinterSettings.PrinterName = comboBox4.Text;
            palettenzettel.PrinterSettings.DefaultPageSettings.PaperSize = pS;
            palettenzettel.PrintPage += new PrintPageEventHandler(palettenzettel_PrintPage);
            
            if (print && comboBox4.Text != "")
            {
                palettenzettel.Print();
                palettenzettel.Print();
            }
            
        }

        //
        // Eventhandler für Ausdruck Palettenzettel
        //
        private void palettenzettel_PrintPage(object sender, PrintPageEventArgs e)
        {

            SolidBrush brush = new SolidBrush(Color.Black);
            System.Drawing.Font header = new System.Drawing.Font(FontFamily.GenericSansSerif, 40.0F, FontStyle.Bold);

            e.Graphics.DrawString("S697 - Quantum of the Seas", header, brush, 50, 50);
            e.Graphics.DrawString("Venue: " + comboBox1.Text, header, brush, 50, 200);
            e.Graphics.DrawString("Package No.: " + textBox3.Text, header, brush, 50, 350);
            e.Graphics.DrawString("Date: " + DateTime.Now.ToString(), header, brush, 50, 500);

            // Logo
            e.Graphics.DrawImage(Worktool.Properties.Resources.ASC_Logo_quadratisch, 600, 600, 200, 200);
            



        }

        //
        // Booking ein und ausschalten
        //
        private void button9_Click(object sender, EventArgs e)
        {
            if (booking)
            {
                button9.Text = "Booking Off";
                button9.BackColor = Color.Red;
                booking = !booking;
            }
            else
            {
                button9.Text = "Booking On";
                button9.BackColor = Color.Green;
                booking = !booking;
            }
        }

        //
        // Manuelle Eingabe im Material
        //
        private void dataGridView3_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

            //if (e.ColumnIndex != dataGridView3.Columns["dgv3packstueck"].Index)
            //{
            //    this.dataGridView3.CurrentRow.Cells["dgv3packstueck"].Value = textBox3.Text;
            //}
            this.vwengMaterialDetailBindingSource.EndEdit();
            try
            {
                this.vw_eng_MaterialDetailTableAdapter.updateMaterialDetail(dataGridView3.CurrentRow.Cells["dgv3Seriennummer"].Value.ToString(), Convert.ToInt32(dataGridView3.CurrentRow.Cells["iDDataGridViewTextBoxColumn1"].Value));
                this.vw_eng_MaterialDetailTableAdapter.updateMaterialExtended(dataGridView3.CurrentRow.Cells["dgv3packstueck"].Value.ToString(), Convert.ToInt32(dataGridView3.CurrentRow.Cells["IDMaterialExtended"].Value));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler: Konnte Seriennummer und/oder Packstück nicht in die DB schreiben");
            }

        }

        //
        // Packstücknummer -1
        //
        private void button10_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(textBox3.Text) > 0)
            {
                textBox3.Text = (Convert.ToInt32(textBox3.Text) - 1).ToString();
            }
        }

        //
        // Packstücknummer +1
        //
        private void button11_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(button12.Text) > Convert.ToInt32(textBox3.Text))
            {
                textBox3.Text = (Convert.ToInt32(textBox3.Text) + 1).ToString();
            }
        }

        //
        // Ausgewählten Artikel ausdrucken
        //
        private void button13_Click(object sender, EventArgs e)
        {

            if (dataGridView3.SelectedRows.Count == 1)
            {
                indexPosition = dataGridView3.SelectedRows[0].Index;
                // Zugehöriges Label ausdrucken
                labelSerialNumber = dataGridView3.Rows[indexPosition].Cells["dgv3Seriennummer"].Value.ToString();
                labelManufacturer = dataGridView3.Rows[indexPosition].Cells["dgv3Manufacturer"].Value.ToString();
                labelModel = dataGridView3.Rows[indexPosition].Cells["dgv3Model"].Value.ToString();
                labelPosition = dataGridView3.Rows[indexPosition].Cells["dgv3Position"].Value.ToString();
                labelVenue = dataGridView3.Rows[indexPosition].Cells["dgv3Venue"].Value.ToString();
                labelJLM = dataGridView3.Rows[indexPosition].Cells["dgv3JLM"].Value.ToString();
                labelTa1 = dataGridView3.Rows[indexPosition].Cells["dgv3Ta1"].Value.ToString();
                labelTa2 = dataGridView3.Rows[indexPosition].Cells["dgv3Ta2"].Value.ToString();
                labelTa3 = dataGridView3.Rows[indexPosition].Cells["dgv3Ta3"].Value.ToString();

                label = new PrintDocument();
                PaperSize pS = new PaperSize("Custom Size", 620, 350);
                label.DefaultPageSettings.PaperSize = pS;
                label.PrinterSettings.PrinterName = comboBox3.Text;
                label.PrinterSettings.DefaultPageSettings.PaperSize = pS;
                label.PrintPage += new PrintPageEventHandler(label_PrintPage);

                if (comboBox3.Text != "")
                {
                    label.Print();
                }

                // Log schreiben
                dataGridView4.Rows.Add();
                dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Time"].Value = DateTime.Now.ToShortTimeString();
                dataGridView4.Rows[dataGridView4.RowCount - 1].Cells["Event"].Value = " Label for Serial " + textBox1.Text + " printed again ";
                textBox1.Text = "";
            }
        }

        private void button14_Click(object sender, EventArgs e)
        {
            // und Packzettel für Palette ausdrucken
            palettenzettel = new PrintDocument();
            PaperSize pS = new PaperSize();
            pS.RawKind = (int)PaperKind.A4Rotated;
            palettenzettel.DefaultPageSettings.PaperSize = pS;
            palettenzettel.PrinterSettings.PrinterName = comboBox4.Text;
            palettenzettel.PrinterSettings.DefaultPageSettings.PaperSize = pS;
            palettenzettel.PrintPage += new PrintPageEventHandler(palettenzettel_PrintPage);

            if (comboBox4.Text != "")
            {
                palettenzettel.Print();
            }
        }

        private void button15_Click(object sender, EventArgs e)
        {
            this.vw_comm_SerialsTableAdapter.Fill(this.aSCDataSet.vw_comm_Serials);
            this.vw_lbl_SerialsTableAdapter.Fill(this.aSCDataSet.vw_lbl_Serials);
            this.vw_eng_MaterialDetailTableAdapter.Fill(this.aSCDataSet.vw_eng_MaterialDetail);
            this.vw_comm_materialTotalTableAdapter.Fill(this.aSCDataSet.vw_comm_materialTotal);
            
            // Die Ansichten entsprechend vorfiltern
            vwcommmaterialTotalBindingSource.Filter = string.Format("isBulk = 1");
            // Starteinstellungen ohne Venue und ohne Packstücke
            vwengMaterialDetailBindingSource.Filter = string.Format("Venue LIKE '{0}'",comboBox1.Text);
        }

    }
}
